//
//  WXPay.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/12/11.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay



public enum WXPayResult:Int
{
    case ok = 0
    case canle = -2
    case failed = -1
    case notice_failed = 4
    
}
public var PayTaskTypeKey:String = "PayTaskType"



public class FastWXPay: NSObject,MoPayRealization{
    public var name: String = "微信支付"
    
    public var ID: String = "wx"
    
    public func pay(pay_id: String, task_type: String, _ sign: NSMutableDictionary, finish_block: @escaping (DoPayReuslt, String, String) -> Void) {
        
        FastWXPay.shared.pay(sign, task_type: task_type, finish_block: { (_result, _task_type, reason) in
                       switch _result{
                       case .ok:
                           finish_block(.ok(.wx), _task_type, pay_id)
                       case .canle:
                           finish_block(.canle(.wx), _task_type, pay_id)
                       case .failed:
                           finish_block(.failed(.wx,reason), _task_type, pay_id)
                       default:
                           finish_block(.failed(.ali,reason), _task_type, pay_id)
                       }
                   })
    }
    

    public static func isWXAppInstalled() -> Bool {
        var installed = WXApi.isWXAppInstalled()
        if !installed
        {
            if let url = URL(string: "weixin://"){
                if UIApplication.shared.canOpenURL(url)
                {
                    installed = true
                }
            }
        }
        return installed
    }
    
//    if([UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"])
//    {
//    NSLog(@"wechat is install");
//    }
//    else
//    {
//    NSLog(@"wechat is not install");
//    }
    
    public struct Static {
        static var instance:FastWXPay? = nil
        static var token:Int = 0
    }
    
    @objc public static var shared:FastWXPay{
        if Static.instance == nil{
            Static.instance = FastWXPay()
        }
        return Static.instance!
    }
    
    public required override init() {
        super.init()
    }
    
    
    
    public var finish_block:((WXPayResult,String,String)-> Void) = {_,_,_ in}
    public var checkTime:Int = 0
    
    @objc public func payCallBack(
        
        info:NSMutableDictionary) {
        
        print("00000S------",info)
        let code = info[int:"code",-1]
        let payCode = WXPayCode(rawValue: code) ?? .errCodeCommon
        
        
        var taskType:String = ""

        if let type_s = UserDefaults.standard.object(forKey: PayTaskTypeKey) as? String
        {
            taskType = type_s
        }
        
        self.checkTime += 1
        switch payCode {
        case .success:
            if let _ = UserDefaults.standard.object(forKey: PayTaskTypeKey)
            {
                self.finish_block(.ok,taskType,payCode.message)
            }
        case .errCodeUserCancel:
            self.finish_block(.canle,taskType,payCode.message)
        default:
            self.finish_block(WXPayResult.failed,taskType,payCode.message)

        }
     
        
    }
    
    
    
    public func  pay(_ info:NSMutableDictionary,task_type:String,finish_block:@escaping (WXPayResult,String,String)-> Void) {
        
        debugPrint("wx_pay|\(info)")
        UserDefaults.standard.set(task_type, forKey: PayTaskTypeKey)
        
        
        self.checkTime = 0
        self.finish_block = finish_block
        
        let time = info["timestamp","0"]
        let partnerId = info["partnerid",""]
        let prepayId = info["prepayid",""]
        let sign = info["sign",""]
        let nonceStr = info["noncestr",""]
        let package = info["package",""]
        
        let req = PayReq()
        req.partnerId = partnerId
        req.prepayId = prepayId
        req.nonceStr = nonceStr
        let i_time = Int(time)!
        req.timeStamp = UInt32(i_time)
        req.package = package
        req.sign = sign
        WXApi.send(req)
        
        //
        debugPrint("partnerId|\(partnerId)----prepayId|\(sign)-----timeStamp|\(i_time)----nonceStr|\(nonceStr)----prepayId|\(prepayId)----package|\(package)")
    }
    
    
}
